package com.leyou.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.PageResult;
import com.leyou.pojo.Brand;
import com.leyou.pojo.BrandVo;
import com.leyou.pojo.Category;
import com.leyou.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("brand")
public class BrandController {
    @Autowired
    private BrandService brandService;
    @RequestMapping("page")
    public ResponseEntity<PageResult<Brand>> page(
            @RequestParam(value = "key",required = false)String key,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "5")Integer rows,
            @RequestParam(value = "sortBy",required = false)String sortBy,
            @RequestParam(value = "desc",required = false)Boolean desc
    ){
        //开启分页
        PageHelper.startPage(page,rows);
        List<Brand>list= this.brandService.searchBrand(key,page,rows,sortBy,desc);
        PageInfo<Brand> pageInfo = new PageInfo<>(list);
        PageResult<Brand> brandPageResult= new PageResult<Brand>(pageInfo.getTotal(), pageInfo.getList());
        return ResponseEntity.ok(brandPageResult);
    }
    //品牌删除
    @RequestMapping("deleteById/{id}")
    public void deleteById(@PathVariable("id")Integer id){

        this.brandService.deleteById(id);
    }
   //新增品牌
    @PostMapping("addOrEditBrand")
    public void addOrEditBrand(@RequestBody BrandVo brandVo){
        String[] split = brandVo.getCids().split(",");
        Brand brand = new Brand(brandVo.getId(), brandVo.getName(), brandVo.getImage(), brandVo.getLetter());
        brandService.addBrand(brand,split);
    }
    //根据bid获取回显所有的分类
    @RequestMapping("bid/{id}")
    public List<Category>getCategoryById(@PathVariable("id")Integer id){
        List<Category>list=brandService.getCategoryById(id);
        return list;
    }

    //修改
    @PutMapping("addOrEditBrand")
    public void update(@RequestBody BrandVo brandVo){
        Brand brand = new Brand(brandVo.getId(), brandVo.getName(), brandVo.getImage(), brandVo.getLetter());
        String[] split = brandVo.getCids().split(",");
        brandService.updateBrand(brand,split);

    }
    //根据商品分类查询品牌
    @RequestMapping("cid/{cid}")
    public List<Brand>getBrandByCid(@PathVariable("cid") Integer cid){
        List<Brand> list= brandService.getBrandByCid(cid);
        return list;
    }

    @RequestMapping("findBrandById/{bid}")
    public Brand findBrandById(@RequestParam("bid") Integer bid){
        Brand brand=  brandService.findBrandById(bid);
        return brand;
    }


}
